
package com.eportal.controller.background;

import com.alibaba.fastjson.JSONObject;
import com.eportal.domain.Sysopt;
import com.eportal.domain.TuserWallet;
import com.eportal.entity.TCommodityEntity;
import com.eportal.params.background.mall.Tcommodity.CommodityParam;
import com.eportal.params.background.mall.Tcommodity.CommodityParamList;
import com.eportal.service.TCommodityService;
import com.eportal.service.UserWalletService;
import com.eportal.vo.controller.background.commodity.QueryStatusNumsVO;
import com.framework.jqgrid.PageEntity;
import com.github.pagehelper.PageInfo;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;


/**
 * 商品管理
 * Created by Saber on 2017/7/13 下午5:19
 */
@Controller
@RequestMapping("/admin/mall/commodity")
public class TCommodityController {


	private Logger logger = LoggerFactory.getLogger(TCommodityController.class);

    @Autowired
    private TCommodityService tCommodityService;
    @Autowired
    private UserWalletService userWalletService;

    @RequestMapping("a.json")
    @ResponseBody
    public JSONObject index() throws Exception {
        JSONObject json = new JSONObject();
        json.put("code",1);
        json.put("msg","欢迎进入首页");
        json.put("a",getOptId());
        return json;
    }

    /**
     * 商户查询列表页
     * @author Saber
     * @Date 2017/7/24 上午10:17
     * @param pageEntity
     * @param commodityParamList
     * @return
     */
    @RequestMapping("list.json")
    @ResponseBody
    public JSONObject queryForPage(PageEntity pageEntity,CommodityParamList commodityParamList){
        JSONObject json = new JSONObject();
        try {
            PageInfo<TCommodityEntity> pageInfo =  tCommodityService.queryForPage(pageEntity,commodityParamList,getOptId(),getOwnerId());
            json.put("code",1);
            json.put("msg","OK");
            json.put("data",pageInfo.getList());
            return json;
        }catch (Exception e){
            logger.error("查询列表时异常",e);
            json.put("code",0);
            json.put("msg","服务器异常:"+e.getMessage());
            return json;
        }
    }

    /**
     * 查询商品各状态数量
     * 所有商品(20)  上架商品(19)  下架商品(1)  已售完（0)）
     * @author Saber
     * @Date 2017/7/24 下午1:04
     * @return
     */
    @RequestMapping(value = "queryStatusNums.json")
    @ResponseBody
    public JSONObject queryStatusNums(){
        JSONObject json = new JSONObject();
        try {
            QueryStatusNumsVO nums = tCommodityService.queryStatusNums(getOptId(),getOwnerId());
            json.put("code",1);
            json.put("msg","OK");
            json.put("data",nums);
            return json;
        }catch (Exception e){
            logger.error("查询列表时异常",e);
            json.put("code",0);
            json.put("msg","服务器异常:"+e.getMessage());
            json.put("data",null);
            return json;
        }

    }

    /**
     * 添加商品
     * @author Saber
     * @Date 2017/8/4 上午9:08
     * @param commodityParam     参数
     * @return
     */
	@RequestMapping(value = "add.json",method = RequestMethod.POST)
	@ResponseBody
    public JSONObject add(CommodityParam commodityParam){

        JSONObject json = new JSONObject();
        try {

            logger.debug("param = " + commodityParam.toString());
            json = tCommodityService.commodityAdd(commodityParam,getOptId(),getOwnerId());
            return json;
        }catch (Exception e){
            e.printStackTrace();
            logger.error("商品添加异常",e);

            json.put("code", 0);
            json.put("msg","添加商品异常");
            return json;
        }
    }

    /**
     * 上传图片
     * @author Saber
     * @Date 2017/7/13 下午5:14
     * @param file 图片
     * @return {'code':'1','msg':'ok','url':'http://xxxxx.xxx/xxxx.jpg,http://xxxx.xxx/xxxx.jpg'}
     *         {'code':'0','msg':'服务器异常:e','url':null}
     */
    @RequestMapping(value = "uploadImg.json",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject uploadImg(@RequestParam(value = "file",required = true) MultipartFile[] file){

        JSONObject json = new JSONObject();
        json.put("code",1);
        StringBuffer url = new StringBuffer();
        //调用单个上传方法
        for (MultipartFile multipartFile : file) {
            JSONObject fileJSON = saveFile(multipartFile);
            if(fileJSON.getIntValue("code")==1){
                url.append(",").append(fileJSON.getString("url"));
            }else {
                //todo 需考虑多图上传的时候 部分上传失败的情况 Created by Saber on 2017/7/31 上午10:00
                /**
                 * do something...
                 */
            }
        }
        json.put("msg","ok");
        json.put("url",url.toString().replaceFirst(",",""));//去掉第一个 ,

        return json;
    }

    /**
     * 删除图片
     * @author Saber
     * @Date 2017/7/13 下午5:15
     * @param url 图片路径
     */
    @RequestMapping(value = "deleteImg.json")
    @ResponseBody
    public JSONObject deleteImg(@RequestParam("url")String url){
        JSONObject json = new JSONObject();

        try {
            try {
                //todo 是否需要对域名做处理?
                //删除
                FileUtils.forceDelete(new File(url));
            } catch (IOException e1) {
                e1.printStackTrace();
            }

            json.put("code",1);
            json.put("msg","删除成功");
            return json;
        }catch (Exception e){
            logger.error("删除图片异常",e);
            json.put("code",1);
            json.put("msg","删除成功");
            return json;
        }

    }


    /**
     * 上架
     * @author Saber
     * @Date 2017/7/24 上午11:11
     * @param sIds  商品id 以,分隔
     * @return
     */
    @RequestMapping(value = "/up.json")
    @ResponseBody
    public JSONObject up(@RequestParam("sIds") String sIds){

        return tCommodityService.up(sIds,getOptId(),getOwnerId());
    }

    /**
     * 下架
     * @author Saber
     * @Date 2017/7/24 上午11:11
     * @param sIds 商品id 以,分割
     * @return
     */
    @RequestMapping(value = "/down.json")
    @ResponseBody
    public JSONObject down(@RequestParam("sIds") String sIds){

        return tCommodityService.down(sIds,getOptId(),getOwnerId());
    }

    /**
     * 删除
     * @author Saber
     * @Date 2017/7/24 上午11:13
     * @param sIds  商品id 以,分割
     * @return
     */
    @RequestMapping(value = "/delete.json")
    @ResponseBody
    public JSONObject delete(@RequestParam("sIds") String sIds){

        return tCommodityService.delete(sIds,getOptId(),getOwnerId());
    }




    /**
     * 获取ownerId
     * @Author Saber
     * @Date 2017/7/10 下午4:28
     * @return
     * @throws Exception
     */
    public String getOwnerId(){
        Sysopt user = (Sysopt) getSession().getAttribute("user");
        TuserWallet wallet = null;
        try {
            wallet = userWalletService.getOrcreateWallet(user.getrLevel(), user.getAgtCode(), user.getCommunityId());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取ownerId异常",e);
        }
        String ownerid = wallet.getWid().toString();
        return ownerid;
    }

    /**
     * 获取用户id
     * @Author Saber
     * @Date 2017/7/10 下午6:59
     * @return 用户id
     */
    public Long getOptId(){
        Sysopt user = (Sysopt) getSession().getAttribute("user");
        return user.getSid();
    }

    private HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    private HttpSession getSession() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();
    }


    /***
     * 保存文件
     * @param file
     * @return
     */
    private JSONObject saveFile(MultipartFile file) {
        JSONObject json = new JSONObject();
        // 判断文件是否为空
        if (!file.isEmpty()) {
            try {
                //文件名
                String oldfileName = file.getOriginalFilename();
                // 文件保存路径
                String rootPath = getSession().getServletContext().getRealPath("/");//获取项目路径
                //图片文件夹以当天日期命名
                String imageDir = "commodity";
//                String imageDir = new SimpleDateFormat("yyyyMMdd").format(new Date());
                //格式化文件名
                String fileName = "commodity_"+ UUID.randomUUID().toString().replace("-", "") + "."+ FilenameUtils.getExtension(oldfileName);
                String filePath = rootPath+ File.separator +".."+File.separator+"upload"+File.separator+imageDir;//与项目同级
//                String filePath = rootPath +".."+ File.separator+"upload"+File.separator+"wangbaImgs"+File.separator+imageDir;//与项目同级
                //文件存放路径
                String url = File.separator+"upload"+File.separator+"file"+File.separator;
                //文件名
//                String destDir = getRequest().getServletContext().getRealPath(url);

                //创建文件夹
//                FileUtils.forceMkdir(new File(destDir));
                FileUtils.forceMkdir(new File(filePath));

//                file.transferTo(new File(destDir+File.separator+filename));
                file.transferTo(new File(filePath + File.separator + fileName));
                //压缩图片
//                Im4JavaUtils.resize(filePath + File.separator + fileName, filePath + File.separator + fileName, 500, 500, 100d, false);
                json.put("code", 1);
                json.put("msg","ok");
//                json.put("url", filePath + File.separator + fileName);
                json.put("url", File.separator+"upload"+File.separator+imageDir+fileName);
//                json.put("url", WebUtil.getReqPreUrl(getRequest())+(url+fileName).replace(File.separator, "/"));
                json.put("data", null);
                return json;
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("文件上传异常",e);
                json.put("code", 0);
                json.put("msg","服务器异常："+e.getMessage());
                json.put("data",null);
                json.put("url", null);
                return json;
            }
        }
        return json;
    }


}
